package com.sspku.weinotes.security;

import com.sspku.weinotes.entity.User;
import com.sspku.weinotes.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Optional;

@Component
@Order(1)
@WebFilter(filterName = "SecurityFilter", urlPatterns = "/*")
public class SecurityFilter implements Filter {
    private static final String LOGIN_URL = "/login";
    private static final String LOGOUT_URL = "/logout";
    private static final String USERNAME_PARAMETER = "username";
    private static final String PASSWORD_PARAMETER = "password";
    private static final String LOGIN_METHOD = "POST";
    private static final String USER_SESSION_KEY = "user";
    private static final String[] RELEASE_ARRAY = {"/registered", "/get_code", "/forget_get_code", "/forget_password"};

    private final UserMapper userMapper;

    @Autowired
    public SecurityFilter(UserMapper  userDao) {
        this.userMapper = userDao;
    }

    @Override
    public void init(FilterConfig filterConfig) {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse resp = (HttpServletResponse) response;
        HttpServletRequest req = (HttpServletRequest) request;
        if ("OPTIONS".equals(req.getMethod())) {
            resp.setHeader("Access-Control-Allow-Credentials", "true");
            resp.setHeader("Access-Control-Allow-Origin", "http://localhost:8081"); //只有8081端口的程序可以访问
            resp.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS,DELETE,PUT,PATCH");
            resp.setHeader("Access-Control-Allow-Headers", req.getHeader("Access-Control-Request-Headers"));
            return;
        }
        for (String release : RELEASE_ARRAY) { //注册 获取验证码，修改密码验证码不需要拦截
            if (release.equals(req.getServletPath())) {
                chain.doFilter(request, response);
                return;
            }
        }
        if (LOGIN_URL.equals(req.getServletPath())) {
            if (!LOGIN_METHOD.equals(req.getMethod())) {
                SecurityUtils.setResponseMsg("不支持该方法", HttpStatus.METHOD_NOT_ALLOWED.value(), 405, resp);
                return;
            }
            String username = req.getParameter(USERNAME_PARAMETER);
            String password = req.getParameter(PASSWORD_PARAMETER);
            Optional<User> user = this.loadUserByUserName(username);
            if (!user.isPresent()) {
                SecurityUtils.setResponseMsg("用户不存在", HttpStatus.OK.value(), 400, resp);
            } else {
                User logInUser = user.get();
                if (logInUser.getPassword().equals(password)) {
                    HttpSession session = req.getSession();
                    session.setAttribute(USER_SESSION_KEY, logInUser);//sesson增加用户 "user"
                    SecurityUtils.setUser(session.getId(), logInUser);//服务器中存储已登录的用户
                    SecurityUtils.setResponseMsg("登陆成功", logInUser, HttpStatus.OK.value(), 200, resp);
                } else {
                    SecurityUtils.setResponseMsg("密码错误", HttpStatus.OK.value(), 400, resp);
                }
            }
        } else if (LOGOUT_URL.equals(req.getServletPath())) {
            HttpSession session = req.getSession();
            SecurityUtils.deleteUser(session.getId());//服务器中删除已登录的用户
            session.invalidate(); //session无效
            SecurityUtils.setResponseMsg("退出成功", HttpStatus.OK.value(), 200, resp);
        } else {
            //检查Session是否存在
            if (req.getSession().getAttribute(USER_SESSION_KEY) != null) {
                chain.doFilter(request, response);
            } else {
                SecurityUtils.setResponseMsg("请先登陆", HttpStatus.UNAUTHORIZED.value(), 401, resp);
            }
        }
    }

    @Override
    public void destroy() {

    }

    private Optional<User> loadUserByUserName(String username) {
        return Optional.ofNullable(userMapper.findByUsername(username));
    }
}
